<template>
  <div class="zn-wrapper v-add-wrapper">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="基本" name="base">
        <el-row>
          <el-col :span="4">
            <div class="zn-form-item zn-form-title">基本信息</div>
          </el-col>
          <el-col :span="20">
            <div class="zn-form-item zn-form-content">
              <el-form ref="addForm" :rules="goodRules" :status-icon="true" label-width="100px" size="small" :model="goodObj">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input v-model="goodObj.goodsName"></el-input>
                </el-form-item>
                <el-form-item label="关键词">
                  <el-input v-model="goodObj.keywords"></el-input>
                  <p class="tips">商品关键字,能准确搜到商品的,空格分割,比如 : 海尔电视 电视 之类的</p>
                </el-form-item>
                <el-form-item label="商品分类" >
                  <el-cascader
                    placeholder = "请选择分类"
                    @change="handleItemChange"
                    :props="props"
                    :options="cateOptions">
                  </el-cascader>
                </el-form-item>
                <el-form-item label="商品图片">
                  <el-input style = "width:60%;float:left" :disabled="true"  placeholder="上传图片"></el-input>
                  <el-button type="primary" @click="openPicModel">选择图片</el-button>
                  <!-- 图片弹框 -->
                  <uploadModel :dialogVisible="dialogVisible" @uploadArr="uploadArr" @visible="visibleChange"></uploadModel>
                  <div class ="tips" style="display: inline-block;">第一张为缩略图，建议为正方型图片，其他为详情页面图片，尺寸建议宽度为640，并保持图片大小一致
                  您可以拖动图片改变其显示顺序</div>
                  <div class="uploadBlock">
                    <div class="uploadImg" v-for="(item,index) in showImgArr" :key="index" v-bind:style="{backgroundImage:'url('+item.path+')'}">
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <div class="zn-form-item zn-form-title">商品信息</div>
          </el-col>
          <el-col :span="20">
            <div class="zn-form-item zn-form-content">
              <el-form ref="addForm" :rules="goodRules" :status-icon="true" label-width="100px" size="small" :model="goodObj">
                <el-form-item label="商品价格" prop="name2">
                  <span class="left col99">售价</span>
                  <el-input v-model="goodObj.price" class="left" style="width:80px;"></el-input>
                   <span class="left col99">原价</span>
                  <el-input v-model="goodObj.marketPrice" class="left" style="width:80px;"></el-input>
                  <span class="left col99">成本价</span>
                  <el-input v-model="goodObj.costPrice" class="left" style="width:80px;"></el-input>
                  <div class="tips">尽量填写完整，有助于于商品销售的数据分析</div>
                </el-form-item>
                <el-form-item label="所在地">
                  <el-select @change = 'getCitys' v-model="goodObj.province"  placeholder="请选择省">
                    <el-option
                      v-for="item in provinces"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select  v-model="goodObj.city"  placeholder="请选择市">
                    <el-option
                      v-for="item in citys"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="标签">
                  <el-input></el-input>
                </el-form-item> -->
              </el-form>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="库存/规格" name="stock">
          <el-row>
          <el-col :span="4">
            <div class="zn-form-item zn-form-title">库存/规格</div>
          </el-col>
          <el-col :span="20">
            <div class="zn-form-item zn-form-content">
                <div class="my-form">
                  <div class="my-form-item">
                      <div class="my-form-item-title">编码</div>
                      <div class="my-form-item-content">
                          <div class="my-form-item-content-code">
                              <!-- <span class="input-group-addon">编码</span>
                              <el-input class="left" :disabled="goodObj.startSpecCheck"  style="width:80px;"></el-input> -->
                              <span class="input-group-addon">条码</span>
                              <el-input class="left" :disabled="goodObj.startSpecCheck" v-model="goodObj.barCode"  style="width:80px;"></el-input>
                              <span class="input-group-addon">重量</span>
                              <el-input class="left" v-model="goodObj.weight" :disabled="goodObj.startSpecCheck" style="width:80px;"></el-input>
                              <span class="input-group-addon">克</span>
                          </div>
                      </div>
                  </div>
                  <div class="my-form-item">
                      <div class="my-form-item-title">库存</div>
                      <div class="my-form-item-content">
                         <div>
                            <el-input :disabled="goodObj.startSpecCheck" v-model="goodObj.stock" class="left" style="width:180px;"></el-input>
                         </div>
                         <div style="margin-top:20px" class="tips">商品的剩余数量, 如启用多规格或为虚拟卡密产品，则此处设置无效.</div>
                         <div style="margin-top:30px">
                           <el-checkbox @change = "startSpec" v-model="goodObj.startSpecCheck">启用商品规格</el-checkbox>
                         </div>
                         <div style="margin-top:10px" class="tips">启用商品规格后，商品的价格及库存以商品规格为准,库存设置为0则会到”已售罄“中，手机也不会显示, -1为不限制</div>
                      </div>
                  </div>
                  <div v-if="goodObj.startSpecCheck" class="my-form-item">
                      <div  class="specs">
                          <div v-for="(item,index) in specArr" :key = "index" class="spec-item">
                              <div class="spec-item-top">
                                  <el-input v-model="item.specName" placeholder="规格名称(比如:颜色)" class="left" style="width:72%;"></el-input>
                                  <el-button @click = "addSpecItem(item,index)" type="primary">+ 添加规格项</el-button>
                                  <el-button style = "margin-left:-4px;" @click = "deleteSpec(item,index)" type="danger">X</el-button>
                              </div>
                              <div class="spec-item-content">
                                  <div v-for="(value,idx) in item.specValues" :key="idx" class="spec-item-content-item">
                                      <!-- 删除按钮 -->
                                      <!-- <div class="input-box-delete el-icon-error" -->
                                            <!-- @click="deleteInputBox"></div> -->
                                      <!-- 输入框 -->
                                      <el-input v-model="value.specValue"
                                                @blur = "blurChange"
                                                placeholder="请输入">
                                      </el-input>
                                  </div>
                              </div>
                          </div>
                      </div>
                  </div>
                  <div v-if="goodObj.startSpecCheck" class="my-form-item">
                      <el-button @click = 'addSpec' type="primary">+ 添加规格</el-button>
                  </div>
                </div>
                <div id="createTable"></div>
                <!-- <div @click = "getData">获取数据</div> -->
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- <el-tab-pane label="参数" name="param"></el-tab-pane> -->
      <el-tab-pane label="详情" name="detail">
        <el-row>
          <el-col :span="4">
            <div class="zn-form-item zn-form-title">内容</div>
          </el-col>
          <el-col :span="20">
            <div class="zn-form-item zn-form-content">
                <ceditor v-model="goodObj.body"></ceditor>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <div class="zn-add-ops">
      <el-button v-if="activeTab == 'detail'" type="primary" size="small" @click="onSave('addForm')">保存</el-button>
    </div>
  </div>
</template>

<script>
  import $ from 'jquery'
  import uploadModel from '@/components/uploadModel/index.vue'
  import local from './local';
  import {addProduct} from '@/api/good.service.js'
  import ceditor from "./quillEditorComponent.vue"
  import cateApi from "@/api/cateGory.service.js";
  import areaApi from "@/api/areas.service.js"
import { debuglog } from 'util';
  export default {
    components:{ceditor, uploadModel},
    data() {
      return {
        showImgArr: [], // 展示图片list
        dialogVisible: false, //控制图片弹框
        activeTab: "base",
        goodObj: {
          goodsName: "", //商品名称
          keywords:'',//关键词
          city:null,//城市
          province:null,//省份
          score:0,//得分,用于排序
          sellerIds:null,//下载数据用户
          costPrice:'',//成本价
          marketPrice:'',//市场价
          price:'',//销售价
          body:'',//描述
          freightTemplateId:0,//运费id暂时无
          hasSku:0,//0:没有,1:有
          startSpecCheck:false,//是否启动规格
          skuList:[],//
          sourceType:0,//来源类型,0:淘宝,1:天猫
          sourceUrl:null,//来源URL
          status:1,//状态,0:下架,1:上架
          stock:'',//库存
          weight:'',//重量
          picture:'',//商品主图
          goodsParamList:[],//商品参数信息
          goodsSpecVoList:[],//商品规格信息
          body:'',//富文本内容
          catId1:null,
          catId2:null,
          catId3:null,
          catId4:null,
          catId5:null,
          barCode:'',//条码
        },
        props:{
          value: 'id',
          label:'name',
          children: 'goodsCats'
        },
        goodRules: {
          goodsName: [
            { required: true, message: "商品名称不能为空", trigger: "blur" }
          ]
        },
        cateOptions:[],
        provinces:[],
        citys:[],
        specArr:[],
        skuObject:null,
        skuArr:[]
      };
    },
    created(){
      this.$i18n.mergeLocaleMessage('en', local.en)
      this.$i18n.mergeLocaleMessage('zh', local.zh)
      this.$i18n.mergeLocaleMessage('ko', local.ko)
      cateApi.getCateList().then((res) =>{
        this.cateOptions = res.values
      })
      let areaParams = {
        pageNo:1,
        pageSize:1000,
        type:2
      }
      areaApi.proList(areaParams).then((res) =>{
        this.provinces = res.values
      })
      
    },
    mounted(){
      this.initSkuObjc()
    },
    methods: {
      uploadArr (data) {
        this.showImgArr = data
      },
      //关闭弹框
      visibleChange () {
        this.dialogVisible = false
      },
      // 打开图片弹框
      openPicModel() {
        this.dialogVisible = true;
      },
      //获取市
      getCitys(){
        let req = {
          pageNo:1,
          pageSize:1000,
          parentId:this.goodObj.province
        }
        areaApi.cityList(req).then((res) =>{
          this.citys = res.values
        })
      },
      initSkuObjc(){
        const vm = this
        this.skuObject = {
            createTable: function () {
                var specArray = []// 盛放每组选中的CheckBox值的对象
                var titleArray = new Array();// 表格标题数组
                var titleIndex = 0;//规格项目下标
                var columnArray = new Array(); // 指定列，用来合并哪些列
                vm.skuObject.mergeTable();//合并表格
                //遍历规格
                vm.specArr.map((item,index) =>{
                    columnArray.push(index);
                    let checkedLength = 0
                    let hasContentMap = []
                    item.specValues.map((val) =>{
                        if (val.specValue){
                            checkedLength++
                            hasContentMap.push(val)
                        }
                    })
                    if (checkedLength >0){
                        titleArray[titleIndex] = item.specName
                        let specValueArray = new Array();//存放规格值的数组
                        hasContentMap.map((val,j) =>{
                            let spec = {
                                spId: item.id,
                                spName: item.specName,
                                specValueId: val.id,
                                specValueName: val.specValue,
                            };
                            //将规格值放入数组中
                            specValueArray[j] = spec;
                        })
                        specArray[titleIndex] = specValueArray;
                        titleIndex++
                    }
                })
                let arr = vm.skuObject.getSkuTr(specArray);
                vm.skuArr = arr
                //开始生成表格
                if (typeof arr != 'undefined') {
                    $('#createTable').html('');
                    var table = $('<table class="table table-bordered" style="border-collapse: collapse;"></table>');
                    table.appendTo($('#createTable'));
                    var thead = $('<thead></thead>');
                    thead.appendTo(table);
                    var trHead = $('<tr></tr>');
                    trHead.appendTo(thead);

                    //创建表头
                    var str = ""
                    $.each(titleArray, function (index, item) {
                        str += '<th style = "width:60px;">' + item + '</th>';
                    });
                    str += "<th style = 'width:60px;'>售价</th><th style = 'width:60px;'>原价</th><th style = 'width:60px;'>成本价</th> <th style = 'width:60px;'>库存</th><th style = 'width:60px;'>重量</th><th style = 'width:60px;'>条形码</th>";
                    trHead.append(str);
                    var tbody = $('<tbody></tbody>');
                    tbody.appendTo(table);
                    //创建行
                    $.each(arr, function (index, item) {
                        var specValItem = item.specValueName.split(",");
                        // console.log(specValItem)
                        var tr = $('<tr name="skuDo" sp-id=' + item.spId + ' sp-name=' + item.spName + ' sp-val-name=' + item.specValueName + ' sp-val-id="' + item.specValueId + '" value="' + item.specValueId + '"></tr>');
                        tr.appendTo(tbody);
                        var str = '';
                        $.each(specValItem, function (i, data) {
                            str += '<td>' + data + '</td>';
                        });
                        let tempId;
                        if (item.spId){
                          tempId = item.spId.split(",").join('')
                        }else {
                          tempId = index
                        }
                        str += `<td ><input type="number" id = "input"   class="${tempId}" placeholder="售价"/></td>`;
                        str += `<td ><input type="number" id = "input"   class="${tempId}" placeholder="原价"/></td>`;
                        str += `<td><input type="number" id = "input"   class="${tempId}" placeholder="成本价"/></td>`;
                        str += `<td><input type="number" id = "input" class="${tempId}" placeholder="库存"/></td>`;
                        str += `<td><input type="number" id = "input"   class="${tempId}" placeholder="重量"/></td>`;
                        str += `<td><input type="number" id = "input" class="${tempId}" placeholder="条形码"/></td>`;
                        tr.append(str);
                    });
                    //结束创建Table表
                    columnArray.pop(); //删除数组中最后一项
                    //合并单元格
                    $(table).mergeCell({
                    // 目前只有cols这么一个配置项, 用数组表示列的索引,从0开始
                    cols: columnArray
                    });
                } else {
                    $('#createTable').html('');
                }
            },

            getSkuTr: function (arr) {
                var a = 1;
                for (var r = 0; r < arr.length; r++) {
                    a *= arr[r].length;
                }
                var newArray = arr[0]
                for (var m = 1; m < arr.length; m++) {
                    var arr2 = arr[m];
                    newArray = vm.skuObject.dosku(newArray, arr2)
                }
                return newArray;
            },
            dosku: function (arr, arr2) {
                var a = arr.length;
                var b = arr2.length;
                var newArr = new Array(a * b);
                var q = 0;
                for (var i = 0; i < arr.length; i++) {
                    for (var j = 0; j < arr2.length; j++) {
                        var spec = {
                            // spId: arr[i].spId + ',' + arr2[j].spId,
                            spId: i + ',' + j,
                            spName: arr[i].spName + ',' + arr2[j].spName,
                            // specValueId: arr[i].specValueId + ',' + arr2[j].specValueId,
                            specValueId: (i+1) + ',' + (j+1),
                            specValueName: arr[i].specValueName + ',' + arr2[j].specValueName,
                            unit:'',
                        };
                        newArr[q] = spec;
                        q++;
                    }
                }
                return newArr;
            },
            mergeTable: function () {
                $.fn.mergeCell = function (options) {
                    return this.each(function () {
                    var cols = options.cols;
                    for (var i = cols.length - 1; cols[i] != undefined; i--) {
                        mergeCell($(this), cols[i]);
                    }
                    dispose($(this));
                    })
                };
                function mergeCell($table, colIndex) {
                    $table.data('col-content', ''); // 存放单元格内容
                    $table.data('col-rowspan', 1); // 存放计算的rowspan值 默认为1
                    $table.data('col-td', $()); // 存放发现的第一个与前一行比较结果不同td(jQuery封装过的), 默认一个"空"的jquery对象
                    $table.data('trNum', $('tbody tr', $table).length); // 要处理表格的总行数, 用于最后一行做特殊处理时进行判断之用
                    // 进行"扫面"处理 关键是定位col-td, 和其对应的rowspan
                    $('tbody tr', $table).each(function (index) {
                    // td:eq中的colIndex即列索引
                    var $td = $('td:eq(' + colIndex + ')', this);
                    // 获取单元格的当前内容
                    var currentContent = $td.html();
                    // 第一次时走次分支
                    if ($table.data('col-content') == '') {
                        $table.data('col-content', currentContent);
                        $table.data('col-td', $td);
                    } else {
                        // 上一行与当前行内容相同
                        if ($table.data('col-content') == currentContent) {
                        // 上一行与当前行内容相同则col-rowspan累加, 保存新值
                        var rowspan = $table.data('col-rowspan') + 1;
                        $table.data('col-rowspan', rowspan);
                        // 值得注意的是 如果用了$td.remove()就会对其他列的处理造成影响
                        $td.hide();
                        // 最后一行的情况比较特殊一点
                        // 比如最后2行 td中的内容是一样的, 那么到最后一行就应该把此时的col-td里保存的td设置rowspan
                        // 最后一行不会向下判断是否有不同的内容
                        if (++index == $table.data('trNum'))
                            $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
                        }
                        // 上一行与当前行内容不同
                        else {
                        // col-rowspan默认为1, 如果统计出的col-rowspan没有变化, 不处理
                        if ($table.data('col-rowspan') != 1) {
                            $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
                        }
                        // 保存第一次出现不同内容的td, 和其内容, 重置col-rowspan
                        $table.data('col-td', $td);
                        $table.data('col-content', $td.html());
                        $table.data('col-rowspan', 1);
                        }
                    }
                    })
            }
            function dispose($table) {
                $table.removeData();
            }
        }
        }
      },
      //选择分类调用
      handleItemChange(val){
        this.goodObj.catId1 = val[0]
      },
      handleTabClick() {},
      onSave(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            if (this.goodObj.startSpecCheck){
              this.goodObj.hasSku = 1
            }
            let imgArr = []
            this.showImgArr.map((item) =>{
              imgArr.push(item.path)
            })
            this.goodObj.picture = imgArr.join(',')
            // delete this.goodObj.startSpecCheck
            // delete this.goodObj.barCode
            
            this.goodObj.skuList = this.handleSkuArr()
            this.goodObj.goodsSpecVoList = this.specArr
            addProduct(this.goodObj).then((res) =>{
                this.$message({type:"success",message:"添加成功"})
            })

          } else {
            return false;
          }
        });
      },
      //input  输入框离开时执行
      blurChange(){
        this.skuObject.createTable()
      },
      handleSkuArr(){
          let  skuArr = []
          console.log(this.skuArr)
          this.skuArr.map((item,index) =>{
              let tempClass = ''
              if (item.spId){
                tempClass ='.'+item.spId.split(',').join('')
              }else {
                tempClass ='.'+index
              }
              // item.
              item.price = $(tempClass).eq(0).val()
              item.marketPrice = $(tempClass).eq(1).val()
              item.costPrice = $(tempClass).eq(2).val()
              item.stock = $(tempClass).eq(3).val()
              item.weight = $(tempClass).eq(4).val()
              item.barCode = $(tempClass).eq(5).val()
              item.skuName = item.specValueName.split(',').join('+')
              skuArr.push(item)
          })
          return skuArr
      },
      //开启规格项
      startSpec(){

      },
      //添加规格项
      addSpecItem(item,index){
        item.specValues.push({specValue:''})
        this.$set(this.specArr,index,item)
      },
      // 删除规格
      deleteSpec(item,index){
        this.specArr.splice(index,1)
        this.skuObject.createTable()
      },
      //添加规格
      addSpec(){
        this.specArr.push({
          specName:'',
          specValues:[],
        })
      }
    }
  };
</script>

<style scoped>
  .zn-wrapper {
    width: 1220px;
    margin: 0 auto;
  }
  .v-add-wrapper .zn-form-item {
    padding: 10px;
  }
  .v-add-wrapper .zn-form-content {
    border-left: 3px solid #fff;
  }
  .left {
    float: left;
  }
  .col99 {
    color: #999;
  }
  .my-form-item {
    display: flex;
    margin-bottom:18px;
  }
  .my-form-item .my-form-item-title {
    width: 100px;
    color: #606266;
    font-size: 14px;
    margin-right: 10px;
    padding-top: 10px;
    text-align: right;
  }
  .my-form-item .my-form-item-content {
    flex: 1;
    text-align: left;
    display: flex;
    flex-direction: column;
    color: #999;
  }
  .my-form-item-content-code {
    display: flex;
    align-items: center;
  }
  .input-group-addon {
    border-radius: 1px;
    font-size: 12px;
    font-weight: 400;
    padding: 6px 12px;
    text-align: center;
  }
  .specs {
    width:100%;
  }
  .spec-item {
    padding: 10px 5px;
    border:1px solid #e7eaec;
    margin-bottom: 10px;
    overflow: hidden;
  }
  .spec-item-content-item {
    position: relative;
    width: 13%;
    margin-right: 30px;
  }
  .spec-item-content-item .input-box-delete {
        position: absolute;
        width: 15px;
        height: 15px;
        top: 0;
        right: 0;
        transform: translate(0, -50%);
        z-index: 33;
        display: none;
    }
    .spec-item-content {
      display: flex;
      margin-top: 30px;
    }
    .spec-item-content-item .input-box-delete:hover {

    }
  

  .table td, .table th {
      vertical-align: middle;
    }
    .title{padding: 10px;background-color: #eaeaea}

    .value-content{
      padding: 10px;
      overflow: hidden;
    }
    .value-content .value-content-item{
        float: left;
        width: 100px;
        margin-left: 50px;
    }

</style>
<style>
  .v-add-wrapper .el-row {
    background: #f8f8f8;
    margin-bottom: 10px;
  }
  .specs .el-button {
    height: 32px;
    line-height: 5px;
  }

  .v-add-wrapper .el-form {
    width: 100%;
    display: inline-block;
  }

  .v-add-wrapper .el-tabs__header {
    margin-bottom: 30px;
  }
  .v-add-wrapper .el-cascader {
    width: 100%;
  }
  .v-add-wrapper .el-input {
    width: 70%;
  }
  .v-add-wrapper td,.v-add-wrapper th {
        border: 1px solid #999;
        text-align: center;
        padding: 12px;
        text-align: left;
    }
  .spec-item-content-item .el-input{
    width:100%;
  }
  .zn-wrapper .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  .v-add-wrapper #input {
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 32px;
    line-height: 32px;
    width: 80px;
    font-size: 12px;
    outline: 0;
    padding: 0 15px;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
</style>

